package com.itcast.interceptor;

import com.alibaba.fastjson.JSON;
import com.itcast.health.entity.Result;
import com.itcast.health.pojo.Member;
import com.itcast.health.utils.JedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginHandlerInterceptor implements HandlerInterceptor {
    @Autowired
    JedisUtil jedisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验用户是否登录

        //从请求头获取用户token
        String token = request.getHeader("token");
        if(token == null || token == "" || token.equals("null")){
            //没有登录
            //401 未授权
            noLogin(response);
            return false;
        }
        //从redis获取用户登录信息
        String s = jedisUtil.get(token);
        Member member = JSON.parseObject(s, Member.class);
        if(null == member){
            noLogin(response);
            return false;
        }
        return true;
    }



    private void noLogin(HttpServletResponse response) throws IOException {
        Result result = new Result(false,"没有登录",401);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(JSON.toJSONString(result));
        writer.close();
    }
}
